import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {AtIcon} from 'taro-ui'
import {Image, ScrollView, View} from '@tarojs/components'
import {Good, CityLocation} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {
  IDENTITY_IS_SELLER,
  RESOURCE_URL,
  SCAN_BIND_SELLER,
  SEARCH_GOODS,
  TARO_ENV,
  UPDATE_USER_SHARE_DATE
} from '../../constants/api'
import {autoLocation, setCity} from '../../actions/location'
import {platform} from '../../utils/platform-settting.service'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {user} from "../../utils/user.service";
import Category from "../../pages/index/template/regionalCategory/component/category";
import Share from "../../components/share/share";
import {location as localtionServer} from "../../utils/location.service";
import './search.scss'

type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Search {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class Search extends Component {
  state = {
    searchResult: [],
    tabs: [],
    linkUri: '',
    loadMore: 'loading',
    tabId: -1,
    isUser: true
  }
  page = 1
  total = 0
  length = 10
  canMore = false

  async onPullDownRefresh() {
    this.page = 1
    await this.search(1)
    Taro.stopPullDownRefresh()
  }

  async componentDidShow() {
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({isUser})
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  shareParams = ''

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: '',
      path: this.state.linkUri
    }
  }

  async UNSAFE_componentWillMount() {
    await vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    await localtionServer.autoLocation()
    const setting = await platform.getSetting();
    if (setting && setting.platformName) {
      Taro.setNavigationBarTitle({
        title: setting.platformName
      })
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const isLogin = await user.checkLogin();
      if (isLogin) {
        const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
        isUser = !identityIsSeller.isSeller
      }
    }
    let tabs = [{id: 0, name: '佣金', key: 'commission'}, {id: 1, name: '最新', key: 'newest'}, {id: 2, name: '销量', key: 'sales'}, {id: 3, name: '价格', key: 'price'}]
    if (isUser) { // 用户
      tabs = [{id: 1, name: '最新', key: 'newest'}, {id: 2, name: '销量', key: 'sales'}, {
        id: 3,
        name: '价格',
        key: 'price'
      }]
    }
    let orderType = Taro.getCurrentInstance().router.params.orderType || ''
    const orderBy = Taro.getCurrentInstance().router.params.orderBy || ''
    if (orderType) {
      orderType = Number(orderType)
      const flag = [0,1,2,3,4].indexOf(orderType) > -1
      if (orderType === 4) {
        tabs.push({id: 4, name: '距离', key: 'distance'})
      }
      if (orderBy) {
        this.topOrBottom = orderBy === 'asc' ? 1 : 0
      }
      await this.setStateSync({tabs, isUser, tabId: flag ? orderType : -1})
    }
    this.setState({tabs, isUser})
    await this.search(this.page)
    this.shareParams = await user.getSellerParams()
    let link = `/common/search/searchList?orderType=${orderType}&orderBy=${orderBy}&${this.shareParams}`
    if (process.env.TARO_ENV === 'h5') {
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      link = window.location.origin + link + '&mpkey=' + mpkey
      const shareData = {
        title: platform.info.platformName,
        desc: '旅游线路',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    } else {
      link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
    this.setState({ linkUri: link })
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
  }

  async onReachBottom() {
    if (this.canMore) {
      this.page++
      await this.search(this.page)
    }
  }

  async search(page) {
    Taro.showLoading({title: '加载中', mask: true})
    const ret = await this.getSearchData(page);
    if (ret && ret.length > 0) {
      if (page === 1) {
        this.setState({searchResult: ret})
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({searchResult: [...oldData, ...ret]})
      }
    } else {
      this.canMore = false
    }
    this.setState({loadMore: 'more'})
    Taro.hideLoading()
  }

  async getSearchData(page) {
    const orderBy = this.topOrBottom ? "asc" : "desc"
    if (typeof page != "number") {
      page = this.page + 1
    }
    const data = {
      p: page,
      draw: page,
      s: this.length,
      orderType: this.state.tabId,
      orderBy: orderBy,
      areaId: this.props.location.region_id
    }
    const result = await http.postL<Good[]>(SEARCH_GOODS, data)
    if (!result) {
      return false;
    }
    this.canMore = result.length >= 10
    return result
  }

  tabClick(tabId) {
    if (tabId === 1 || tabId === 0) {
      this.topOrBottom = 0
    } else {
      this.topOrBottom = this.topOrBottom === 0 ? 1 : 0
    }
    this.setState({loadMore: 'loading', tabId, searchResult: []}, async () => {
      this.page = 1
      await this.search(this.page)
    })
  }

  topOrBottom = 1

  keyChange(topOrBottom, tabId) {
    this.topOrBottom = topOrBottom
    this.setState({tabId})
  }

  jump(url) {
    Taro.navigateTo({
      url
    })
  }

  render() {
    const {isUser, searchResult, tabs, tabId, loadMore, linkUri} = this.state
    return (
      <View className='search-root'>
        <GzhAuth />
        <View className='search-top'
          style='position: sticky;top: 0;left: 0;margin-bottom: 10px;border-bottom: 1px solid #f3f3f3;'
        >
          <View className='tabs'>
            <ScrollView scrollX enable-flex className='subNav'>
              <View className='nav-box'>
                {tabs.length > 0 && tabs.map(item =>
                  <View key={item.id} onClick={this.tabClick.bind(this, item.id)}
                    className={`nav-item ${tabId === item.id ? 'active' : ''}`}
                  >
                    <View className='tabs-cat'>
                      <View className='text-name'>
                        {item.name}
                      </View>
                      {(item.key === 'sales' || item.key === 'price' || item.key === 'distance') &&
                      <View className='topOrBottom'>
                        <AtIcon className={`${(this.topOrBottom === 1 && this.state.tabId === item.id) ? 'tab-active' : 'tab-in-active'}`}
                          prefixClass='car'
                          onClick={this.keyChange.bind(this, 0, item.id)} value='iconshangsanjiaoxing' size='12'
                        />
                        <AtIcon className={`${(this.topOrBottom === 0 && this.state.tabId === item.id) ? 'tab-active' : 'tab-in-active'}`}
                          prefixClass='car'
                          onClick={this.keyChange.bind(this, 1, item.id)} value='iconxiasanjiaoxing' size='12'
                        />
                      </View>}
                    </View>
                  </View>
                )}
              </View>
            </ScrollView>
          </View>
        </View>
        {searchResult.length > 0 && <Category data={searchResult} isUser={isUser} />}
        {searchResult.length <= 0 && loadMore !== 'loading' && <View className='listNull' style='margin-top: 20%;'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`}
            mode={TARO_ENV === 'h5' ? 'widthFix-h5' : 'widthFix'} className='listNull_img'
          />
          <View className='text'>暂无数据</View>
        </View>}
        {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} linkUri={linkUri} />}
      </View>
    )
  }
}

export default Search as ComponentClass<PageOwnProps, PageState>
